<script setup lang="ts">
import { ref, onMounted } from "vue";
import router from "@/router";
import { useRoute } from "vue-router";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { lockTypeList, stocktakingTypeList } from "@/utils/staticData";
import ChargerSelect from "@/components/ChargerSelect";
import { getStocktakingOrderList } from "@/api/stocktakingPlan";
import { useMessage } from "@/hooks/useMessage";

const partStocktakingType = 2; // 抽盘类型
const { createConfirm } = useMessage();
const multiTagsStore = useMultiTagsStoreHook();
const route = useRoute();
const formRef = ref(null);
const form = ref({
  planCode: "", // 盘点计划
  warehouseCode: "", // 盘点仓库
  stocktakingCode: "", // 盘点单号
  leaderUserId: "", // 盘点人员
  stocktakingType: "", // 盘点类型
  lockType: "", // 盘点锁定
  memo: "" // 备注
});
const stocktakingPlans = ref([]); // 盘点计划列表
const warehouseList = ref([]); // 仓库列表

const props = defineProps({
  preWarehouseCode: {
    type: [String, Number],
    default: ""
  },
  rows: {
    type: Number,
    default: 0
  }
});

const emits = defineEmits([
  "openChooseMaterialDialog",
  "clearTableData",
  "update:preWarehouseCode"
]);

const { createNotification } = useMessage();

const rules = ref({
  planCode: [{ required: true, message: "请选择盘点计划", trigger: "change" }],
  warehouseCode: [
    { required: true, message: "请选择盘点仓库", trigger: "change" }
  ],
  leaderUserId: [
    { required: true, message: "请选择盘点人员", trigger: "change" }
  ],
  stocktakingType: [
    { required: true, message: "请选择盘点类型", trigger: "change" }
  ],
  lockType: [{ required: true, message: "请选择盘点锁定", trigger: "change" }],
  memo: [{ required: true, message: "请输入盘点备注", trigger: "blur" }]
});

const goBack = () => {
  multiTagsStore.handleTags("splice", route.path);
  router.back();
};

// 导入明细
const importDetail = () => {
  if (props.rows > 0) {
    createNotification({
      message: "请清除导入后再重新导入",
      type: "error"
    });
    return;
  }
  if (!form.value.stocktakingType) {
    createNotification({
      message: "请先选定盘点类型",
      type: "error"
    });
    return;
  }
  if (form.value.stocktakingType === partStocktakingType) {
    if (form.value.warehouseCode) {
      emits("openChooseMaterialDialog");
    } else {
      createNotification({
        message: "请先选定盘点仓库",
        type: "error"
      });
    }
  }
};

// 清除导入
const handleReset = () => {
  emits("clearTableData");
};

/**
 * 盘点计划选择事件
 * @param val 盘点计划编码
 */
const handlePlanChange = (val: string) => {
  const result = stocktakingPlans.value.find(
    (item: any) => item.planCode === val
  );
  // 更改盘点计划时，重设盘点仓库列表后清空盘点仓库
  warehouseList.value = result.warehouses || [];
  form.value.warehouseCode = "";
};

/**
 * 仓库选择事件
 * @param val 仓库编码
 */
const handleWarehouseChange = (val: string | number) => {
  if (props.rows && !!props.preWarehouseCode) {
    createConfirm({
      message: "更换仓库后，将清空现有物料明细列表中的内容，是否继续？",
      center: false
    })
      .then(() => {
        emits("update:preWarehouseCode", val);
      })
      .catch(() => {
        form.value.warehouseCode = props.preWarehouseCode;
      });
  } else {
    emits("update:preWarehouseCode", val);
  }
};

onMounted(() => {
  getStocktakingOrderList().then(res => {
    stocktakingPlans.value = res.data?.stocktakingPlans || [];
  });
});

defineExpose({
  getForm: () => {
    return form.value;
  },
  validateForm: () => {
    return new Promise((resolve, reject) => {
      formRef.value.validate((valid: any) => {
        if (valid) resolve(true);
        else reject(false);
      });
    });
  }
});
</script>

<template>
  <div class="applyForm">
    <div class="flex items-center justify-between flex-row pb-[16px]">
      <p class="text-[16px] font-bold">调拨管理信息</p>
      <el-button @click="goBack"
        ><svg-icon name="rollback" size="16" />&nbsp;返回</el-button
      >
    </div>
    <el-form
      ref="formRef"
      class="mb-[-16px]"
      :model="form"
      :rules="rules"
      inline
    >
      <el-form-item label="盘点计划" prop="planCode">
        <el-select
          v-model="form.planCode"
          placeholder="请输入"
          filterable
          @change="handlePlanChange"
          clearable
        >
          <el-option
            v-for="(item, index) in stocktakingPlans"
            :key="index"
            :label="item.planCode"
            :value="item.planCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="盘点仓库" prop="warehouseCode">
        <el-select
          v-model="form.warehouseCode"
          filterable
          placeholder="请输入"
          @change="handleWarehouseChange"
          clearable
        >
          <el-option
            v-for="(item, index) in warehouseList"
            :key="index"
            :value="item.warehouseCode"
            :label="item.warehouseName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="盘点单号" prop="stocktakingCode">
        <el-input
          v-model="form.stocktakingCode"
          disabled
          placeholder="系统自动带入"
        />
      </el-form-item>
      <el-form-item label="盘点人员" prop="leaderUserId">
        <ChargerSelect v-model:value="form.leaderUserId" />
      </el-form-item>
      <el-form-item label="盘点类型" prop="stocktakingType">
        <el-select
          v-model="form.stocktakingType"
          filterable
          placeholder="请输入"
          clearable
        >
          <el-option
            v-for="(item, index) in stocktakingTypeList"
            :key="index"
            v-bind="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="盘点锁定" prop="lockType">
        <el-select v-model="form.lockType" filterable placeholder="请输入" clearable>
          <el-option
            v-for="(item, index) in lockTypeList"
            :key="index"
            v-bind="item"
          />
        </el-select>
      </el-form-item>
      <div class="inline-flex">
        <el-form-item label="盘点备注" prop="memo">
          <el-input
            v-model="form.memo"
            type="textarea"
            maxlength="500"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-button type="primary" @click="importDetail">导入明细</el-button>
        <el-button @click="handleReset">清除导入</el-button>
        <span class="ml-[17px]">
          <i class="error-tag">!</i>
          <span class="tag">（根据盘点类型导入待盘明细）</span>
        </span>
      </div>
    </el-form>
  </div>
</template>
<style scoped lang="scss">
.applyForm {
  overflow: hidden;
  .el-textarea {
    --el-textarea-height: 32px;
  }
  .error-tag {
    display: inline-flex;
    width: 17.5px;
    height: 17.5px;
    border-radius: 17.5px;
    background-color: #ed7b2f;
    color: #fff;
    font-size: 12px;
    align-items: center;
    justify-content: center;
    font-style: normal;
  }
  .tag {
    line-height: 36px;
    font-style: normal;
    font-size: 12px;
    color: rgba(0, 0, 0, 0.6);
  }
}
</style>
